package com.liuweiheng.springcloud.auth;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuweiheng.base.exception.TokenException;
import com.liuweiheng.springcloud.jwt.JwtUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;

/**
 * jwtToken拦截器
 * @author lwh
 * @since 2020/12/7
 */

@Component
@ConfigurationProperties("ort.my.jwt")
@Setter
@Getter
@Slf4j
public class JwtTokenFilter implements GlobalFilter, Ordered {

    private String[] skipAuthUrls;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain){
        String url = exchange.getRequest().getURI().getPath();

        // 跳过不需要验证的路径
        if (null != skipAuthUrls && Arrays.asList(skipAuthUrls).contains(url)) {
            return chain.filter(exchange);
        }

        // 从请求头中获取token
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        ServerHttpResponse response = exchange.getResponse();
        if (StrUtil.isBlank(token)) {
            // 没有token，返回错误信息
            throw new TokenException("请登录");
        }

        // 检查token
        try {
            boolean isAuth = JwtUtil.checkToken(token);
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
